package com.itheima.sky.controller.front;

import com.itheima.sky.entity.Result;
import com.itheima.sky.pojo.ShoppingCart;
import com.itheima.sky.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description ShoppingCartController
 * @Author jiangning
 * @Date 2024-06-29
 */
@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    ShoppingCartService shoppingCartService;

    @GetMapping("/list")
    public Result getUserCartList(HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        List<ShoppingCart> cart = shoppingCartService.getCartByUserId(userId);
        return Result.success(cart);
    }

    //c
    //增加购物车商品
    @PostMapping("/add")
    public Result addCartList(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
//        Long userId=1111111L;
        shoppingCart.setUserId(userId);
        ShoppingCart cartList=shoppingCartService.addCartListByUserId(shoppingCart);
        return Result.success(cartList);
    }

    //删除购物车
    @DeleteMapping("/clean")
    public Result cleanCartList(HttpSession session, @RequestBody(required = false) Map<String,String> map){
        Long userId = (Long) session.getAttribute("userId");
        //根据菜id删除列表
        if(map==null){
//            System.out.println("delete");
//           //delete
//            shoppingCartService.deleteCart(setmeal_id);
            shoppingCartService.cleanUpCart(userId);
            return Result.success(null);
        }

        Long setmeal_id = Long.parseLong(map.get("setmealId"));
        //update
        System.out.println("update");
//            shoppingCartService.cleanCartList(userId);
//            Integer updatedNum = shoppingCartService.getNumber(setmeal_id);
        shoppingCartService.subCart(setmeal_id,userId);
        Integer updatedNum = shoppingCartService.getCount(setmeal_id,userId);
        Map<String,Object> res = new HashMap<>();
        res.put("number",updatedNum);
        return Result.success(res);

    }

}
